package com.yang.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

public class MyServer {
	
	private ServerSocket server;
	private int port;
	private String filePath;
	public MyServer(){
		init(true);
	}
	private void init(boolean isFilePath) {
		Properties pp=new Properties();
		try {
			pp.load(this.getClass().getClassLoader().getResourceAsStream("cfg.Properties"));
			port=Integer.parseInt(pp.getProperty("port"));
			server=new ServerSocket(port);
			Socket socket=server.accept();
			
			if(isFilePath){
				InputStream is=socket.getInputStream();
				InputStreamReader read=new InputStreamReader(is,"utf-8");
				BufferedReader reader=new BufferedReader(read);
				filePath=reader.readLine();
				reader.close();
				read.close();
				is.close();
				socket.close();
				server.close();
			}else{
				InputStream is=socket.getInputStream();
				filePath="e"+filePath.substring(1);
				File file=new File(filePath);
				File fi=new File(filePath.substring(0,filePath.lastIndexOf("\\")));
				if(!file.exists()||(!fi.exists())){
					fi.mkdirs();
					file.createNewFile();
				}
				OutputStream os=new FileOutputStream(file);
				byte[] buf=new byte[1024];
				int len=0;
				while((len=is.read(buf))!=-1){
					os.write(buf, 0, len);
				}
				os.flush();
				os.close();
				is.close();
				
				socket.close();
				server.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		init(!isFilePath);
		
	}
	public static void main(String[] args) {
		new MyServer();
	}

}
